﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Transactions;
using CN.DBML;
using CN.Commons;
using CN.Contents;

namespace CN.BusLineImport
{
    public partial class FormBusLineImport : Form
    {
        private static  string cityNavigationConnectionStr = System.Configuration.ConfigurationManager.ConnectionStrings["CityNavigationConnectionString"].ToString();
        private CityNavigationDataContext _cNDC = new CityNavigationDataContext(cityNavigationConnectionStr); 
        public FormBusLineImport()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 导入公交路线
        /// 公交线路的格式：
        /// 线路名称,起点站,起点站首班时间,起点站末班时间,终点站,终点站首班时间,终点站末班时间,类型,上行,下行
        /// </summary>
        /// <param name="data">得到提供的公交路线</param>
        /// <returns></returns>
        private bool importDataByOne(string data)
        {
            bool isSucceed = false;            
            string[] dataArr = data.Split(',');
            //新建公交路线实例
            BusLine busLine = new BusLine();
            DateTime dtNow = DateTime.Now;
            busLine.AddTime = dtNow;
            
            busLine.LineName = dataArr[0];
            busLine.FirstStation = dataArr[1];
            busLine.FirstBeginTime = dataArr[2];
            busLine.FirstEndTime = dataArr[3];
            busLine.LastStation = dataArr[4];
            busLine.LastBeginTime = dataArr[5];
            busLine.LastEndTime = dataArr[6];
            busLine.ScopeType = EnumHelper.ParseEnumValueByString<ScopeType>(dataArr[7]);

            //循环得到线路站点
            List<BusPassStation> bpStationList = new List<BusPassStation>();
            BusPassStation bpStation = null;
            int sn = 0;
            //上行
            foreach (string item in dataArr[8].Split('-'))
            {
                bpStation = new BusPassStation();
                bpStation.LineName = dataArr[0];
                bpStation.SerialNum = sn;
                bpStation.StationName = item;
                bpStation.DirectionType = 1;
                bpStationList.Add(bpStation);
                sn++;
            }
            if (dataArr.Length == 10)
            {
                sn = 0;
                //下行
                foreach (string item in dataArr[9].Split('-'))
                {
                    bpStation = new BusPassStation();
                    bpStation.LineName = dataArr[0];
                    bpStation.SerialNum = sn;
                    bpStation.StationName = item;
                    bpStation.DirectionType = 2;
                    bpStationList.Add(bpStation);
                    sn++;
                }
            }

            this._cNDC.BusLines.InsertOnSubmit(busLine);
            this._cNDC.BusPassStations.InsertAllOnSubmit(bpStationList);

            try
            {
                isSucceed = this._cNDC.SubmitChangesWithReturnValue();
            }
            catch (Exception)
            {
                isSucceed = false;
            }
            return isSucceed;
        }

        /// <summary>
        /// 批量导入公交路线
        /// 公交线路的格式：
        /// 线路名称,起点站,起点站首班时间,起点站末班时间,终点站,终点站首班时间,终点站末班时间,类型,上行,下行
        /// </summary>
        /// <returns></returns>
        private bool importDataByTxt()
        {
            bool isSucceed = false;
            List<BusPassStation> bpStationList = new List<BusPassStation>();
            List<BusLine> busLineList = new List<BusLine>();
            
            using (StreamReader sr = new StreamReader(this.tbxPath.Text, Encoding.Default))
            {
                String busLineStr = string.Empty;

                while ((busLineStr = sr.ReadLine()) != null)
                {
                    BusLine busLine = new BusLine();
                    string[] dataArr = busLineStr.Split(',');
                    
                    DateTime dtNow = DateTime.Now;
                    busLine.AddTime = dtNow;

                    busLine.LineName = dataArr[0];
                    busLine.FirstStation = dataArr[1];
                    busLine.FirstBeginTime = dataArr[2];
                    busLine.FirstEndTime = dataArr[3];
                    busLine.LastStation = dataArr[4];
                    busLine.LastBeginTime = dataArr[5];
                    busLine.LastEndTime = dataArr[6];
                    busLine.ScopeType = EnumHelper.ParseEnumValueByString<ScopeType>(dataArr[7]);
                    busLineList.Add(busLine);

                    BusPassStation bpStation = null;
                    int sn = 0;
                    //上行
                    foreach (string item in dataArr[8].Split('-'))
                    {
                        bpStation = new BusPassStation();
                        bpStation.LineName = dataArr[0];
                        bpStation.SerialNum = sn;
                        bpStation.StationName = item;
                        bpStation.DirectionType = 1;
                        bpStationList.Add(bpStation);
                        sn++;
                    }
                    if (dataArr.Length == 10)
                    {
                        sn = 0;
                        //下行
                        foreach (string item in dataArr[9].Split('-'))
                        {
                            bpStation = new BusPassStation();
                            bpStation.LineName = dataArr[0];
                            bpStation.SerialNum = sn;
                            bpStation.StationName = item;
                            bpStation.DirectionType = 2;
                            bpStationList.Add(bpStation);
                            sn++;
                        }
                    }
                }
            }

            this._cNDC.BusLines.InsertAllOnSubmit(busLineList);
            this._cNDC.BusPassStations.InsertAllOnSubmit(bpStationList);

            try
            {
                isSucceed = this._cNDC.SubmitChangesWithReturnValue();
            }
            catch (Exception)
            {
                isSucceed = false;
            }
            return isSucceed;
        }

        /// <summary>
        /// 判断公交路线格式是否正确
        /// </summary>
        /// <param name="data">单条公交路线</param>
        /// <returns></returns>
        private bool checkInputStr(string data)
        {
            bool isOk = false;
            if (data.Split(',').Length == 10 && data.Split(',')[8].Contains('-') && data.Split(',')[9].Contains('-'))
            {
                isOk = true;
            }
            else if (data.Split(',').Length == 9 && data.Split(',')[8].Contains('-') && !data.Split(',')[7].Contains('-'))
            {
                isOk = true;
            }
            else
                isOk = false;
            return isOk;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            //单条导入
            if (this.tabControl1.SelectedIndex == 0)
            {
                //判断公交线路格式是否正确
                if (!this.checkInputStr(this.tbxData.Text.Trim()))
                {
                    MessageBox.Show("公交路线格式错误，请核实！");
                    return;
                }
                if (this.importDataByOne(this.tbxData.Text.Trim()))
                    MessageBox.Show(string.Format("公交路线：{0} 导入成功！", this.tbxData.Text.Trim().Split(',')[0]));
                else
                    MessageBox.Show(string.Format("公交路线：{0} 导入失败！", this.tbxData.Text.Trim().Split(',')[0]));

            }
            else//批量导入
            {
                using (StreamReader sr = new StreamReader(this.tbxPath.Text, Encoding.Default))
                {
                    String busLine = string.Empty;

                    while ((busLine = sr.ReadLine()) != null)
                    {
                        //判断公交线路格式是否正确
                        if (!this.checkInputStr(busLine))
                        {
                            MessageBox.Show(string.Format("公交路线：{0} 格式错误，请核实！", busLine.Split(',')[0]));
                            return;
                        }
                    }
                }
                this.lblWait.Visible = true;
                this.Cursor = Cursors.WaitCursor;
                if (this.importDataByTxt())
                {
                    this.Cursor = Cursors.Default;
                    this.lblWait.Visible = false;
                    MessageBox.Show(string.Format("公交路线导入成功"));
                }
                else
                {
                    this.Cursor = Cursors.Default;
                    this.lblWait.Visible = false;
                    MessageBox.Show(string.Format("公交路线导入失败"));
                }
            }
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.tbxPath.Text = openFileDialog1.FileName;
            }
        }
    }
}
